<script>
import { toTaget } from './methods/toTarget.js';
import { getLocation } from './utils/getLocation.js';
import { eventBus } from './utils/eventBus.js';
import { reject } from 'lodash-es';
import { gcj02towgs84, wgs84togcj02 } from 'coordtransform';
import initStorage from './utils/initStorage.js';
import PreloadManager from './utils/PreloadManager.js';
import store from './store';
const linli = uniCloud.importObject('linliChat', { customUI: true });
import showAgain from './utils/showAgain.js';
import { date, object } from './uni_modules/uv-ui-tools/libs/function/test.js';
import { data } from './uni_modules/uview-ui/libs/mixin/mixin.js';
import { getPublicMsg } from './utils/msgAction.js';
import { location2address } from '@/utils/getPois';

export default {
	globalData: {
		appKey: '82hegw5u8p3sx',
		debug: true,
		count: 1,
		sessions: [],
		messageQueue: [],
		audioContext: null,
		isFirstLaunch: true,
		debugShow: false,
		firstLogin: false
	},
	data() {
		return {
			reconnectTimer: null,
			skip: null, //获取记录的条数，预留暂时固定
			lastTime: null, //获取记录的最后时间，预留暂时固定
			unwatch: null
		};
	},

	onShow() {
		console.warn('app show');
		uni.$emit('app_show');
	

		//this.clearBadge();
		if (!this.globalData.isFirstLaunch && !this.globalData.firstLogin) {
			console.log('再次show', this.globalData.isFirstLaunch);
			showAgain();
		}
		this.globalData.isFirstLaunch = false;
	},
	onUnhandledRejection(){
		console.log("promisi错误");
	},
	onHide() {
		console.warn('app hide');
		uni.setStorageSync('user', this.$store.state.msg.user);
		uni.setStorageSync('lastLocation', this.$store.state.msg.location);
        this.$store.dispatch('msg/setConfig')
		uni.$emit('AppHide');
	},
	onUnload() {
		console.warn('应用已退出');
		uni.setStorageSync('user', this.$store.state.msg.user);
		uni.setStorageSync('lastLocation', this.$store.state.msg.location);
	},
	async onLaunch() {
		console.warn('app onLaunch');
		await initStorage();
		await this.$store.dispatch('msg/getSystemInfo');
		await this.initPush();
		await this.watchLocation();
		uni.onPushMessage((res) => {
			const notic = {
				type: res.type, //预留类型接口
				id: res.id || Date.now().toString(),
				time: res.time || 30000, // 留存时间（毫秒）
				content: res.content || '无更多内容',
				title: res.title || '通知',
				hasAction: res.hasAction || true // 默认显示确认按钮
			};
			uni.$emit('notice', notic);
		});
		PreloadManager.cleanExpiredCache();
		this.globalData.audioContext = uni.createInnerAudioContext();
		this.globalData.audioContext.onError((err) => {
			console.error('音频上下文错误：', err);
		});
	},

	methods: {
		clearBadge() {
			plus.runtime.setBadgeNumber(0);
			console.log('消除角标');
		},

		watchLocation() {
			let lastLngLat = null;
			this.unwatch = store.watch(
				(state) => state.msg.location,
				async (location) => {
					// 1. 先过滤无效位置（原有逻辑保留）
					if (!location || !location.longitude || !location.latitude) {
										return;
					}
					const user = store.state.msg?.user;
					if (!user || !user.userId) {
						return;
					}
					// 2. 对比经纬度是否真正变化（误差小于0.0001视为未变化）
					const currentLngLat = `${location.longitude.toFixed(4)},${location.latitude.toFixed(4)}`;
					if (currentLngLat === lastLngLat) {
						return; // 经纬度未变化，不执行后续逻辑
					}
					lastLngLat = currentLngLat; // 更新上一次经纬度

					console.warn('地址监听开始......（有效变化）');
					try {
						if (!location || typeof location !== 'object' || location.longitude === undefined || location.latitude === undefined) {
							console.warn('watchLocation: 新位置信息无效（缺少 longitude 或 latitude）', location);
							return; // 位置无效，终止执行
						}

						if (
							typeof location.longitude !== 'number' ||
							typeof location.latitude !== 'number' ||
							location.longitude < -180 ||
							location.longitude > 180 ||
							location.latitude < -90 ||
							location.latitude > 90
						) {
							console.warn('watchLocation: 经纬度数值超出合理范围', location);
							return;
						}

						if (!store || !store.state || !store.state.msg) {
							console.error('watchLocation: 状态管理 store 结构不完整（缺少 state 或 msg 模块）');
							return; // 终止执行
						}
						const msgState = store.state.msg;

						const user = msgState.user;
						if (!user || typeof user !== 'object' || !user.userId) {
							// 假设 userId 是用户唯一标识
							console.warn('watchLocation: 用户信息无效（缺少 user 或 userId）', user);
							return; // 无有效用户，不执行后续操作
						}

						if (this.skip === undefined || this.skip === null || isNaN(Number(this.skip))) {
							this.skip = 0;
						} else {
							this.skip = Number(this.skip); // 强制转为数字
						}
                       if (user?.userId) {
                       	try {
                       		const setLocationToPoi = await linli.setLocationToPoi(
                       			user.userId, location, 'lastOnline'
                       		);
                       		if (!setLocationToPoi.code) {
                       			console.error('位置写入Poi失败', JSON.stringify(
                       				setLocationToPoi));
                       		}
                       	} catch (poiErr) {
                       		console.error('位置写入Poi异常：', poiErr);
                       	}
                       }
						await getPublicMsg(location);

						linli.setLocationToPoi(user.userId, location, 'fly');
						const address = await location2address(location);
				
						if (Object.keys(address).length) {
							store.commit('msg/SET_address', address) || '';
						}
					} catch (e) {
						// 捕获所有异常，输出详细上下文
						console.error('watchLocation: 执行失败', {
							error: e.message || JSON.stringify(e),
							stack: e.stack, // 错误堆栈，便于定位
							user: user?.userId, // 仅打印用户标识
							location: location ? `${location.longitude},${location.latitude}` : '无效位置',
							skip: this.skip
						});
					}
				},
				{ immediate: true, deep: true }
			);
		},

		async initPush() {
			try {
				// 获取推送客户端ID
				const res = await uni.getPushClientId();
				const cid = res[1].cid;
				console.log('推送客户端ID:', cid);

				if (!cid) {
					console.error('获取推送客户端ID失败');
					return;
				}

				// 获取完整的系统信息
				const systemInfo = uni.getSystemInfoSync();

				// 获取网络类型
				const networkInfo = await this.getNetworkType();

				// 合并系统信息
				const fullSystemInfo = {
					...systemInfo,
					networkType: networkInfo
				};

				// 上报设备信息到云函数
				const reportResult = await uniCloud.callFunction({
					name: 'reportDevice',
					data: {
						device_id: cid, // 使用CID作为device_id
						system_info: fullSystemInfo
					}
				});

				if (reportResult.result.success) {
					uni.setStorageSync('push_cid', cid);
				} else {
					console.error('设备信息上报失败:', reportResult.result);
				}
			} catch (error) {
				console.error('推送初始化失败:', error);
			}
		},

		// 获取网络类型
		async getNetworkType() {
			return new Promise((resolve) => {
				uni.getNetworkType({
					success: (res) => {
						resolve(res.networkType);
					},
					fail: () => {
						resolve('unknown');
					}
				});
			});
		},

		// 用户登录成功后调用此方法
		async bindDeviceToUser(user) {
			try {
				const { userId, push_clientid } = user;

				if (!push_clientid || !userId) {
					console.error('未找到推送客户端ID', push_clientid, userId);
					return;
				}

				// 更新设备表的用户关联
				const bindResult = await uniCloud.callFunction({
					name: 'bindUserDevice',
					data: {
						user_id: userId,
						device_id: push_clientid
					}
				});

				if (bindResult.result.success) {
					console.log('用户设备绑定成功');
				} else {
					console.error('用户设备绑定失败:', bindResult.result);
				}
			} catch (error) {
				console.error('绑定设备失败:', error);
			}
		},
		async initLocationAndWebSocket() {
			try {
				// 步骤1：获取首次定位（await 等待结果）
				const firstLocation = await store.dispatch('getLocation');
				// 步骤2：获取用户信息（WebSocket 依赖 userTel）
				await store.dispatch('getUserInfo');
				const userTel = store.state.user?.userTel;
				if (!userTel) {
					throw new Error('未获取到用户手机号，无法连接WebSocket');
				}
				// 步骤3：用首次定位+用户信息连接WebSocket
				const isWsConnected = await store.dispatch('connectWebSocket', {
					location: firstLocation,
					userTel: userTel
				});
				if (isWsConnected) {
					console.log('定位+WebSocket 初始化完成');
				}
			} catch (err) {
				console.error('初始化失败：', err);
				this.showTips(err.message);
			}
		},
		showTips(content) {
			uni.showModal({
				title: '初始化异常',
				content: content || '请检查定位和网络状态',
				confirmText: '知道了',
				showCancel: false
			});
		}
	}
};
</script>

<style lang="scss">
@import '@/uni_modules/uview-ui/index.scss';
@import '@/static/iconFont/iconfont.css';
@import '@/uni_modules/uv-ui-tools/index.scss';
</style>
